package com.dayuanit.dy15.lesson21.demo3;

import java.util.Arrays;

public class MyArrayList<E> {

    //存放元素的数组
    private Object[] elementData = new Object[3];

    //当前存放了多少个元素
    private int size;

    public void add(E element) {
        if (size == this.elementData.length) {
            System.out.println("容器已满，进行扩容...");
            //对数组进行扩容 Arrays.copyOf 创建一个新的数组，且将原始数组的数据复制一份到新数组中
            elementData = Arrays.copyOf(this.elementData, this.elementData.length + 2);
        }
        elementData[size] = element;
        size += 1;
    }

    public void remove(int index) {
        if (index >= this.size) {
            System.out.println("数组越界");
            return;
        }

        this.elementData[index] = null;// 设置为null,有利于GC（垃圾回收器）进行对象回收
        //数组的数据迁移
        System.arraycopy(this.elementData, index + 1, this.elementData, index, this.elementData.length - index - 1);
        size --;
    }

    public void set(int index, E newElement) {
        if (index >= this.size) {
            System.out.println("数组越界");
            return;
        }
        this.elementData[index] = newElement;
    }

    public E get(int index) {
        if (index >= this.size) {
            System.out.println("数组越界");
            return null;
        }
        return (E)this.elementData[index];
    }

    public int size() {
        return this.size;
    }
}
